/**
 * 
 */
package com.jcsi.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

import com.mysql.jdbc.DatabaseMetaData;
import com.mysql.jdbc.ResultSetMetaData;

/**
 * @author gahon_a
 *
 */
public class DbManager {
	// Donnees
	public	String				url		=	"";
	public	String				login	=	"";
	public	String				pass		=	"";
	public	String				driver	=	"";
	
	// Connection et etat
	public	Connection		connection	=	null;
	public	Statement		state			=	null;
	
	// Informations
	public	ResultSet					resultSet						= null;
	public	DatabaseMetaData	dbMetaData				= null;
	public	ResultSetMetaData	resultSetMetaData	= null;
	
    private static DbManager	instance;
	
	public static DbManager	getInstance()
	{
		if (null == instance)
			instance = new DbManager();
		return instance;
	}
	
	private	DbManager()
	{
		
	}
	
	private	DbManager(String	xml) 
	{
	}

	public String				Driver()						{	return driver;				}
	public void				Driver(String driver)	{	this.driver = driver;	}

	public String				Url()								{	return url;					}
	public void				Url(String url)			{	this.url = url;				}

	public String				Login()						{	return login;				}
	public void				Login(String login)	{	this.login = login;		}

	public String				Pass()							{	return pass;				}
	public void				Pass(String pass)		{	this.pass = pass;		}

	
	public	void			Connect()
	{	
		try
		{
			Class.forName(this.driver);
			this.connection		=	DriverManager.getConnection(this.url, this.login, this.pass);
			this.state				=	this.connection.createStatement();
			this.dbMetaData	= (DatabaseMetaData) this.connection.getMetaData();
		}
		catch (ClassNotFoundException cnfe)	{	cnfe.printStackTrace();	}
		catch (SQLException sqle)						{	sqle.printStackTrace();	}
		catch(Exception e)									{	e.printStackTrace();		}
	}
	
	public	void			Disconnect()
	{
		try
		{
			this.connection.close();
		}
		catch (Exception e)	{	e.printStackTrace();	}
	}

	public	ResultSet	Execute(String request)
	{
		this.resultSet = null;
		try {	
			if (this.state != null)
				this.resultSet = this.state.executeQuery(request);// SELECT
		} catch (SQLException e) {	e.printStackTrace();	}
		return resultSet;
	}
	
	public	int		ExecuteUpdate(String request)
	{
		int		res = 0;
		try
		{
			if (this.state != null)
				res = this.state.executeUpdate(request); // INSERT UPDATE DELETE
		}
		catch (SQLException e) {	e.printStackTrace();	}
		return res;
	}
}

/* 
<dbconfig name="database">
	<driver>jdbc:...</driver>
	<location></location>
	<identifiant></identifiant>
	<password></password>
</dbconfig>
*/